package gold.digger;

import gold.utils.InputUtil;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC30 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {

        int matchLen;

        public List<Integer> findSubstring(String s, String[] words) {
            Map<String, Integer> dict = new HashMap<>();
            for (String word : words) dict.put(word, dict.getOrDefault(word, 0) + 1);
            matchLen = words[0].length();

            List<Integer> ans = new ArrayList<>();
            for (int i = 0; i <= s.length() - matchLen * dict.size(); i++) {
                Map<String, Integer> curDict = deepCopy(dict);
                if (isPosMatch(s, i, curDict)) ans.add(i);
            }

            return ans;
        }

        public boolean isPosMatch(String s, int i, Map<String, Integer> dict) {
            if (i > s.length() - matchLen * dict.size()) return false;
            if (!dict.containsKey(s.substring(i, i + matchLen))) return false;
            if (dict.get(s.substring(i, i + matchLen)) > 1)
                dict.put(s.substring(i, i + matchLen), dict.get(s.substring(i, i + matchLen)) - 1);
            else dict.remove(s.substring(i, i + matchLen));
            if (dict.isEmpty()) return true;
            return isPosMatch(s, i + matchLen, dict);
        }

        public Map<String, Integer> deepCopy(Map<String, Integer> dict) {
            Map<String, Integer> copy = new HashMap<>();
            for (String word : dict.keySet()) {
                copy.put(word, dict.get(word));
            }
            return copy;
        }
    }

    public void run() {
        System.out.println(new Solution().findSubstring("barfoothefoobarman", new String[]{"foo", "bar"}));
        System.out.println(new Solution().findSubstring("wordgoodgoodgoodbestword", new String[]{"word", "good", "best", "word"}));
        System.out.println(new Solution().findSubstring("barfoofoobarthefoobarman", new String[]{"bar", "foo", "the"}));
    }

    public static void main(String[] args) throws Exception {
        LC30 an = new LC30();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
